import { getCommentList, addCommend } from '@/services/modules/comment';
import { ICommentItem } from '@/types/modules/comment';
import { Effect, Reducer } from 'umi';

export interface CommentModelState {
  commentList: ICommentItem[];
  commentLength: number;
}

export interface CommentPageModelType {
  namespace: 'comment';
  state: CommentModelState;
  effects: {
    getCommentList: Effect;
    AddArticleCommend: Effect;
  };
  reducers: {
    save: Reducer<CommentModelState>;
  };
}

const CommentPageModel: CommentPageModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'comment',

  // 数据模型状态，相当于vuex的state
  state: {
    commentList: [],
    commentLength:0,
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    *getCommentList({ payload }, { call, put }) {
      let result = yield call(getCommentList, payload.id,payload.page);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            commentList: result.data[0],
            commentLength: result.data[1],
          },
        });
      }
    },
     // 提交评论
     *AddArticleCommend({payload}, {call, put}){
      yield call(addCommend, payload);
    },
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default CommentPageModel;
